import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as actions from '../../actions/index'

class Shop extends Component {

    subtract(index) {
        console.log(index)
        this.props.Subtract(index)
    }

    add(index) {
        this.props.Add(index)
    }

    allCheckFlag() {
        this.props.allCheckItem()
    }

    checkFlag(index) {
        this.props.checkItem(index)
    }

    render() { 
        let { shopList, allFlag } = this.props

        let checkedItem = shopList.filter(item => item.flag)

        let addNum = checkedItem.reduce((prev, next) => {
            return prev + next.price * next.count
        }, 0)

        return (
            <div style={{overflowY: 'auto', height: '100%'}}>
                全选：<input type='checkbox' checked={allFlag} onChange={
                    this.allCheckFlag.bind(this)
                }/>
                总价：<span>{addNum}</span>
                <div>
                    {
                        shopList && shopList.length ? shopList.map((item,index) => {
                            return (
                                <div key={index} className='item'>
                                    <input type='checkbox' checked={item.flag} onChange={
                                        this.checkFlag.bind(this,index)
                                    }/>
                                    <img src={item.img} alt='' />
                                    <p>{item.name}</p>
                                    <p>单价：{item.price}</p>
                                    <button style={{padding: '10px 10px'}} onClick={
                                        this.subtract.bind(this,index)
                                    }>-</button>
                                    <span>{item.count}</span>
                                    <button style={{padding: '10px 10px'}} onClick={
                                        this.add.bind(this,index)
                                    }>+</button>
                                </div>
                            )
                        }) : ''
                    }
                </div>
            </div>
        )
    }
}

let mapStateToProps = ({carReducer}) => {
    return {
        ...carReducer
    }
}

let mapDispatchToProps = (dispatch) => bindActionCreators(actions, dispatch)
 
export default connect(mapStateToProps, mapDispatchToProps)(Shop)